<template>
	<div class="echart">

	</div>
</template>
  
<script>
import * as echarts from 'echarts';
 
import icon from '/@/assets/bottleECharts/other-icon.png';

export default {
	name: 'Echart',
	components: {
	},
	props: {
		dataSource: {
			default: null
		}
	},
	data() {
		return {
			timer: null,
			myChart: null,

			title: "",
			geoJSON: {},
			geoData: {},
			seriesData: {},
		};
	},
	watch: {
		dataSource: {
			handler(newVal, a) {
				this.handleDataSource(newVal);
			},
			deep: true,
			immediate: true,
		}
	},
	created() {
	},
	mounted() {
		// 添加窗口大小变化监听
		window.addEventListener('resize', this.resizeChart);
	},
	beforeUnmount() {
		// 组件销毁前，移除事件监听
		window.removeEventListener('resize', this.resizeChart);
	},
	methods: {
		
		handleDataSource(obj) {
			if (!obj) { return; }

			// console.log("当前组件接收数据源为：", obj);

			this.title = obj.title || "";
			this.geoJSON = obj.geoJSON || {};
			this.geoData = obj.geoData || {};
			this.seriesData = obj.seriesData || {};

			this.$nextTick(() => {
				// console.log("当前组件 id 为：", this.$el.id);
				this.initChart();
				this.resizeChart();
			})
		},
		getSeriesForEffectScatter(list, inside=true) {
			var form = {
				type: "effectScatter",
				coordinateSystem: "geo",
				geoIndex: 0,
				z: 11,
				symbol: inside ? "circle" : "image://" + icon,
				symbolSize: inside ? 10 : 30,
				label: {
					show: true,
					position: "bottom",
					formatter: "{b}",
					color: inside ? "#fff" : "#000",
					fontSize: 14,
				},
				data: list.map(item => ({
					...item,
					itemStyle: {
						color: "blue",
					}
				}))
			};
			return form;
		},
		getLines(list) {
			if (!list || !list.length) { return null; }

			var lines = [];
			for (let i = 0; i < list.length; i++) {
				const line = list[i];
				const from = this.seriesData.effectScatterInside.filter(item => item.id === line.from);
				if (!from || from.length !== 1) { continue }
				const to = this.seriesData.effectScatterOutside.filter(item => item.id === line.to);
				if (!to || to.length !== 1) { continue }

				lines.push([from[0].value, to[0].value]);
			}

			if (!lines.length) { return null; }

			var form = {
				type: "lines",
				name: "Route",
				coordinateSystem: "geo",
				geoIndex: 0,
				// polyline: true,
				effect: {
					show: true,
					period: 10,
					constantSpeed: 80,
					color: "#b9ffe7",
					trailLength: 0.5,
				},
				// symbol: 'path://M35.5 40.5c0-22.16 17.84-40 40-40s40 17.84 40 40c0 1.6939-.1042 3.3626-.3067 5H35.8067c-.2025-1.6374-.3067-3.3061-.3067-5zm90.9621-2.6663c-.62-1.4856-.9621-3.1182-.9621-4.8337 0-6.925 5.575-12.5 12.5-12.5s12.5 5.575 12.5 12.5a12.685 12.685 0 0 1-.1529 1.9691l.9537.5506-15.6454 27.0986-.1554-.0897V65.5h-28.7285c-7.318 9.1548-18.587 15-31.2715 15s-23.9535-5.8452-31.2715-15H15.5v-2.8059l-.0937.0437-8.8727-19.0274C2.912 41.5258.5 37.5549.5 33c0-6.925 5.575-12.5 12.5-12.5S25.5 26.075 25.5 33c0 .9035-.0949 1.784-.2753 2.6321L29.8262 45.5h92.2098z'
				symbolSize: 5,
				lineStyle: {
					color: "red",
					width: 5,
					type: "dotted",
					opacity: 1,
					curveness: 0.5,
				},
				label: {
					show: false,
				},
				z: 10,
				data: lines.map(item => ({
					coords: item,
					lineStyle: {
						color: "blue",
					}
				})),
			};
			return form;
		},
		getSeriesForEffectScatterPin(list) {
			var form = {
				type: "effectScatter",
				coordinateSystem: "geo",
				geoIndex: 0,
				z: 12,
				symbol: "pin",
				symbolSize: 20,
				label: {
					show: true,
					position: "top",
					formatter: "{b}",
					color: "yellow",
					fontSize: 14,
				},
				encode: {
              tooltip: 2,
            },
				data: list.map(item => ({
					...item,
				}))
			};
			return form;
		},
		getOption() {
			const option = {
				title: {
					text: this.title,
					left: 'center',
					bottom: 10,
				},
				tooltip: {
					show: true,
					formatter: "{b}", // 只显示 name
					textStyle: {
						fontSize: 16,
					},
				},
				geo: {
					map: "geoMap",    // 使用 registerMap 注册的地图名称
					roam: false,    // 是否开启鼠标缩放和平移漫游
					zoom: 1,    // 当前视角的缩放比例
					scaleLimit: {
						min: 0.5,
						max: 2,
					},    // 滚轮缩放的极限控制，通过 min 和 max 限制最小和最大的缩放值
					// selectedMode: 'single',    // 选中模式，表示是否支持多个选中，默认关闭，支持布尔值和字符串，字符串取值可选'single'表示单选，或者'multiple'表示多选
					label: {
						show: true,    // 是否显示标签
						position: 'top',    // 标签的位置
						distance: 5,    // 距离图形元素的距离
						rotate: 0,    // 标签旋转
						offset: [0, 0],    // 是否对文字进行偏移
						color: '#fff',     // 文字的颜色
						fontSize: 14,    // 文字的字体大小
					},	// 图形上的文本标签
					itemStyle: {
						areaColor: "#16BDFF",     // 地图区域的颜色
						borderColor: "#20b0ff",    // 图形的描边颜色
						borderWidth: 2,    // 描边线宽
						borderType: 'solid',    // 描边类型
						shadowBlur: 10,    // 图形阴影的模糊大小
						shadowColor: 'rgba(0, 0, 0, 0.2)',    // 阴影的颜色
						shadowOffsetX: -1,    // 阴影水平方向上的偏移距离
						shadowOffsetY: 1,    // 阴影垂直方向上的偏移距离
						opacity: 1,    // 图形透明度
					},    // 地图区域的多边形 图形样式
					emphasis: {
						disabled: true,    // 是否关闭高亮状态
						focus: 'self',    // 在高亮图形时，是否淡出其它数据的图形已达到聚焦的效果
						label: {
							show: true,    // 是否显示标签
							color: "#fff",    // 文字的颜色
							fontSize: 10,    // 文字的字体大小
						},
						itemStyle: {
							areaColor: "#1968d3",    // 地图区域的颜色
							borderColor: "#20b0ff",    // 图形的描边颜色
							borderWidth: 2,    // 描边线宽
							borderType: 'dashed',    // 描边类型
						},
					},    // 高亮状态下的多边形和标签样式
					// zlevel: 1,    // 所有图形的 zlevel 值
					regions: this.geoData.regions,    // 在地图中对特定的区域配置样式
				},					
				series: [
					this.getSeriesForEffectScatter(this.seriesData.effectScatterInside),
					this.getSeriesForEffectScatter(this.seriesData.effectScatterOutside, false),
					this.getLines(this.seriesData.lines),
					this.getSeriesForEffectScatterPin(this.seriesData.effectScatterPin),
				]
			};
			return option;
		},
		// 图表初始化
		initChart() {
			var chartDom = document.getElementById(this.$el.id);
			if (!chartDom) {
				return;
			}
			echarts.dispose(chartDom);


			var myChart = echarts.init(chartDom, null, {
				renderer: "canvas",
				useDirtyRect: false,
			});
			this.myChart = myChart;
			echarts.registerMap("geoMap", this.geoJSON, {});

			var option = this.getOption();
      		option && myChart.setOption(option);

			var _this = this;
			myChart.on("click", function (params) {
				event.stopPropagation()

				console.log(params);
				let type = params.componentType;
				let subType = params.componentSubType;
				if (type == "geo") {
					console.log(params.name);
				} else if (type == "series" && subType == "lines") {
					console.log(params.data);
				} else if (type == "series" && subType == "effectScatter") {
					console.log(params.data);
				}
			});
			myChart.getZr().on("click", function (event) {
				let pixelPoint = [event.offsetX, event.offsetY];
				console.log("pixelPoint: " + pixelPoint);
				let chartPoint = myChart.convertFromPixel("geo", pixelPoint);
				console.log("chartPoint: " + chartPoint);
				// 没有 target 意味着鼠标/指针不在任何一个图形元素上，它是从“空白处”触发的。
				if (!event.target) {
				// 点击在了空白处，做些什么。
				}
			});
		},
		// 图表调整大小
		resizeChart() {
			setTimeout(() => {
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					if (this.myChart) {
						// console.log("resize:", this.$el.id);
						this.myChart.resize();
					}
				}, 200);
			})
		}
	}
};
</script>
  
<style scoped lang="scss">
.echart {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-color: #fff;
}
</style>